package io.renren.modules.sys.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.PassWordForm;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;


	/**
	 * 所有用户列表
	 */
	@GetMapping("/getList")
	public R getList(@RequestParam Map<String, Object> params){
		PageUtils page = sysUserService.getList(params);
		return R.ok(page);
	}

	/**
	 * 用户信息
	 */
	@GetMapping("/get")
	public R get(Integer userId){
		SysUserEntity user = sysUserService.getById(userId);
		
		//获取用户所属的角色列表
//		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
//		user.setRoleIdList(roleIdList);
		
		return R.ok(user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/add")
	public R add(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		//创建人
		user.setCreateUserId(this.getUserId());
		sysUserService.saveUser(user);
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	public R update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		sysUserService.update(user);
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	public R delete(@RequestParam(value = "userId") Integer userId) {
		if (1 == userId) {
			return R.error("系统管理员不能删除");
		}
		if (getUserId() == userId) {
			return R.error("当前用户不能删除");
		}
		sysUserService.removeById(userId);
		return R.ok();
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R info(){
		return R.ok().put("user", getUser());
	}

	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R password(@RequestBody PassWordForm form) {
		Assert.isBlank(form.getNewPassWord(), "新密码不为能空");

		//sha256加密
		String passWord = new Sha256Hash(form.getPassWord(), getUser().getSalt()).toHex();
		//sha256加密
		String newPassWord = new Sha256Hash(form.getNewPassWord(), getUser().getSalt()).toHex();

		//更新密码
		boolean flag = sysUserService.updatePassWord(getUserId(), passWord, newPassWord);
		if(!flag){
			return R.error("原密码不正确");
		}

		return R.ok();
	}

}
